package mqttserver

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/sirupsen/logrus"
)

type MQTTConfig struct {
	Broker         string `json:"broker"`
	Port           int    `json:"port"`
	Username       string `json:"username"`
	Password       string `json:"password"`
	PublishTopic   string `json:"publish_topic"`
	SubscribeTopic string `json:"subscribe_topic"`
}

// 创建MQTT客户端
func CreateMQTTClient(mqttConfig MQTTConfig) mqtt.Client {
	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcp://%s:%d", mqttConfig.Broker, mqttConfig.Port))
	opts.SetUsername(mqttConfig.Username)
	opts.SetPassword(mqttConfig.Password)

	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		logrus.Fatal("Failed to connect to MQTT broker:", token.Error())
	}

	return client
}

// 发布消息
func PublishMessage(client mqtt.Client, publishTopic, payload string) {
	logrus.Println("payload: ", payload)
	logrus.Println("publishTopic:", publishTopic)
	token := client.Publish(publishTopic, 0, false, payload)
	token.Wait()
}

// 处理接收到的消息
func ProcessMessage(client mqtt.Client, msg mqtt.Message) string {
	payloadJSON := string(msg.Payload())
	logrus.Info("ProcessMessage: ", string(msg.Payload()))
	return payloadJSON
}

// 执行订阅任务
func PerformSubscription(client mqtt.Client, subscribeTopic string, messageChan chan<- mqtt.Message) {
	client.Subscribe(subscribeTopic, 0, func(client mqtt.Client, msg mqtt.Message) {
		messageChan <- msg // 将接收到的消息发送到通道中
	})
}

// 取消订阅
func CancelSubscription(client mqtt.Client, unsubscribeTopic string, messageChan chan<- mqtt.Message) {
	client.Unsubscribe(unsubscribeTopic)
	close(messageChan) // 关闭消息通道
}

// 处理接收到的消息
func ProcessMsg(client mqtt.Client, msg mqtt.Message) string {
	payloadJSON := string(msg.Payload())
	logrus.Info("ProcessMsg: ", payloadJSON)
	return payloadJSON
}

// 执行订阅任务
func PerformSub(client mqtt.Client, subscribeTopic string, messageChan chan mqtt.Message) {
	client.Subscribe(subscribeTopic, 0, func(client mqtt.Client, msg mqtt.Message) {
		messageChan <- msg // 将接收到的消息发送到通道中
	})
}

// 取消订阅
func CancelSub(client mqtt.Client, unsubscribeTopic string, messageChan chan mqtt.Message) {
	client.Unsubscribe(unsubscribeTopic)
}
